package com.kamistoat.netty.zercopy_new;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * NIO零拷贝客户端
 */
public class NewIOClient {
    public static void main(String[] args) {
        try {
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress("127.0.0.1", 7001));
            String filename = "/home/kamistoat/ubuntu/Netty_Learning/src/main/java/com/kamistoat/netty/zercopy_new/spring-boot-2.4.2.zip";
            // 使用FileInputStream制作一个FileChannel
            FileChannel fileChannel = new FileInputStream(filename).getChannel();
            long startTime = System.currentTimeMillis();

            // fileChannel的transferTo()底层就是用零拷贝实现的，将文件从fileSystemCache直接传递到目标channel
            // 在linux下，一个transferTo 方法就可以完成整个文件的传输
            // 在Windows下，一次transferTo只能传输8M文件，就需要分段传输文件，此时需要主要传输时的分段偏移量
            long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
            System.out.println("总字节数: " + transferCount + ", 耗时: " + (System.currentTimeMillis() - startTime));
            fileChannel.close();
            socketChannel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
